<template>
  <div class="music-content"
       ref="musicLyric">
    <p v-for=" (item,index) in lyric"
       :key="index"
       :class="{active:(currentTime *1000>=item.time && currentTime *1000<item.pre)}">
      {{ item.lrc }}
    </p>
  </div>
</template>

<script>
import { getLyric } from '@/api/RankList'
import { mapState } from 'vuex';
export default {
  data () {
    return {
      Lyrics: {},//歌词
    }
  },
  props: ['musicId', 'active'],
  computed: {
    ...mapState({
      currentTime: (state) => {
        return state.playlist.currentTime;
      },
    }),
    lyric () {
      let arr
      if (this.Lyrics.lyric) {
        arr = this.Lyrics.lyric.split(/[(\r\n)\r\n]+/).map((item, i) => {
          let min = item.slice(1, 3)
          let sec = item.slice(4, 6)
          let mill = item.slice(7, 10)
          let lrc = item.slice(11, item.length)
          let time = parseInt(min) * 60 * 1000 + parseInt(sec) * 1000 + parseInt(mill)
          if (isNaN(Number(mill))) {
            mill = item.slice(7, 9)
            lrc = item.slice(10, item.length)
            time = parseInt(min) * 60 * 1000 + parseInt(sec) * 1000 + parseInt(mill)
          }
          return { min, sec, mill, lrc, time }
        })
      }
      if (arr) {
        arr.forEach((item, i) => {
          if (i === arr.length - 1 || isNaN(arr[i + 1].time)) {
            item.pre = 100000
          } else {
            item.pre = arr[i + 1].time
          }
        });
      }
      return arr
    }
  },
  methods: {
    // 获取歌词
    async getLyrics (value) {
      let res = await getLyric(value)
      if (res.code !== 200) return
      this.Lyrics = res.lrc
    },
  },
  watch: {
    currentTime () {
      let p = document.querySelector("p.active")
      if (p) {
        if (p.offsetTop > 240) {
          this.$refs.musicLyric.scrollTop = p.offsetTop - 240
        }
      }
    },
    active: {
      immediate: true,
      handler (val) {
        if (!val) return
        this.getLyrics(this.musicId)
      }
    },
    musicId (val) {
      /* 监听ID，改变后重新获取数据 */
      console.log('geci的资源ID改变了', this.musicId)
      if (!val) return
      this.hotList = []
      this.getLyrics(this.musicId)
    }
  }
}
</script>

<style scoped lang="less">
.music-content {
  width: 320px;
  height: 369px;
  overflow: auto;
  P {
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
    height: 30px;
    line-height: 30px;
  }
  .active {
    font-weight: bold;
    font-size: 20px;
  }
  /*滚动条高宽度*/
  &::-webkit-scrollbar {
    width: 2px;
    height: 4px;
  }
  /*滚动条滑块*/
  &::-webkit-scrollbar-thumb {
    border-radius: 3px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #f6f4f4;
  }
}
</style>